package com.lagou.study.seckill.controller;

import com.lagou.study.seckill.mapper.StockMapper;
import com.lagou.study.seckill.pojo.Message;
import com.lagou.study.seckill.pojo.Order;
import com.lagou.study.seckill.service.OrderService;
import com.lagou.study.seckill.service.RedisService;
import com.lagou.study.seckill.service.StockService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("seckill")
public class Seckillcontroller {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RedisService redisService;

    @Autowired
    private StockService stockService;

    @Autowired
    private OrderService orderService;

    @PostMapping("click")
    public Message click(HttpServletResponse response) throws InterruptedException {
        if (!redisService.hasKey("stock")){
            Integer quantity = stockService.getQuantity();
            redisService.set("stock", quantity);
        }
        if((Integer)redisService.get("stock")>0){
            String id = UUID.randomUUID().toString();
            rocketMQTemplate.convertAndSend("seckill", id);
            return new Message(id);
        }else {
            redisService.del("stock");
            return new Message("error");
        }
    }

    @PostMapping("pay")
    public Message pay(String id){
        Order order = orderService.findById(id);
        if (new Date(order.getCreateTime().getTime() + 5000).compareTo(new Date()) == -1){
            stockService.sumQuantity();
            redisService.del("stock");
            return new Message("订单支付超时");
        }else {
            orderService.deleteById(id);
            return new Message("秒杀成功");
        }
    }
}
